import { MSG_TYPES } from '../utils/MESSAGE_TYPES'
console.log('content_script inject')

var temp = document.createElement('script');
temp.setAttribute('type', 'text/javascript');
temp.src = chrome.extension.getURL('./inject_scripts/inject.js');
temp.onload = function () {
  this.parentNode.removeChild(this);
};
document.head.appendChild(temp);

const HUNGUP_WINDOWS = {

}

window.addEventListener('message', (msg) => {
  const { data } = msg
  // 直接转发，就是帮inject做转发的
  if ([MSG_TYPES.open, MSG_TYPES.send, MSG_TYPES.setProps, MSG_TYPES.setRequestHeader].includes(data.event)) {
    if (!HUNGUP_WINDOWS[data.id]) {
      HUNGUP_WINDOWS[data.id] = msg.source
    }
    port.postMessage({
      event: data.event,
      id: data.id,
      data: data.data
    });
  } else if (data.event === MSG_TYPES.matchingReq) {
    chrome.runtime.sendMessage({
      event: data.event
    }, function (response) {
      window.postMessage({
        event: MSG_TYPES.matchingUpdate,
        data: response
      })
    });
  }
})


// 长连接
var port = chrome.extension.connect({ name: "knockknock" });

port.onMessage.addListener(function (msg, b, c) {
  const { data, event, id, headers } = msg
  console.log('arg', b, c)
  if (event in MSG_TYPES) {
    switch (event) {
      case MSG_TYPES.response: {
        HUNGUP_WINDOWS[id].postMessage({
          event: MSG_TYPES.response,
          id,
          data: data,
          headers
        })
        // delete HUNGUP_WINDOWS[id]
      }
    }
  }
});

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  const { event, data } = request
  if (event === MSG_TYPES.matchingUpdate) {
    window.postMessage({
      event,
      data
    })
  }
});